//
//
#include"SList.h"
SL* SLBuyNode(SLDataType x) {
	SL* newnode = (SL*)malloc(sizeof(SL));
	if (newnode == NULL) {
		perror("realloc fail!!");
		exit(1);
	}
	newnode->val = x;
	newnode->next = NULL;
	return newnode;
}
void SLPrint(SL* phead) {
	SL* pcur = phead;
	while (pcur) {
		printf("%d->", pcur->val);
		pcur = pcur->next;
	}
	printf("NULL\n");
}
void SLPushBack(SL** pphead, SLDataType x) {
	assert(pphead);
	SL* newnode = SLBuyNode(x);
	if (*pphead == NULL) {
		*pphead = newnode;
	}
	else {
		SL* pcur = *pphead;
		while (pcur->next) {
			pcur = pcur->next;
		}
		pcur->next = newnode;
	}
}
void SLPushFront(SL** pphead, SLDataType x) {
	assert(pphead);
	SL* newnode = SLBuyNode(x);
	newnode->next = *pphead;
	*pphead = newnode;

}
void SLPopBack(SL** pphead) {
	assert(pphead);
	assert(*pphead);
	SL* pcur = *pphead;
	SL* prev = *pphead;
	if ((*pphead)->next == NULL) {
		free(*pphead);
		*pphead = NULL;
	}
	else {
		while (pcur->next) {
			prev = pcur;
			pcur = pcur->next;
		}
		prev->next = NULL;
		free(pcur);
		pcur = NULL;
	}
}
void SLPopFront(SL** pphead) {
	assert(pphead && *pphead);
	SL* next = (*pphead)->next;
	free(*pphead);
	*pphead = next;
}
SL* SLFind(SL* phead, SLDataType x) {
	assert(phead);
	SL* pcur = phead;
	while (pcur) {
		if (pcur->val == x) {
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}
void SLInsert(SL** pphead, SL* pos, SLDataType x) {
	assert(pphead);
	assert(pos);
	if (pos == *pphead) {
		SLPushFront(pphead, x);
	}
	else {
		SL* newnode = SLBuyNode(x);
		SL* prev = *pphead;
		while (prev->next != pos) {
			prev = prev->next;
		}
		newnode->next = prev->next;
		prev->next = newnode;
	}
}
void SLInsertAfter(SL* pos, SLDataType x) {
	assert(pos);
	SL* newnode = SLBuyNode(x);
	newnode->next = pos->next;
	pos->next = newnode;
}
void SLErase(SL** pphead, SL* pos) {
	assert(pos);
	assert(pphead && *pphead);
	if (pos = *pphead) {
		SLPopFront(pphead);
	}
	else {
		SL* prev = *pphead;
		while (prev->next != pos) {
			prev = prev->next;
		}
		prev->next = pos->next;
		free(pos);
		pos = NULL;
	}
}
void SLEraseAfter(SL* pos) {
	assert(pos);
	assert(pos->next);
	SL* del = pos->next;
	pos->next = del->next;
	free(del);
	del = NULL;
}
void SLDestroy(SL** pphead) {
	assert(pphead && *pphead);
	SL* next = (*pphead)->next;
	while (*pphead) {
		free(*pphead);
		*pphead = next;
		if (next) {
			next = next->next;
		}
	}
}